package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.enums.CourseEnum;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.domain.dto.AddCourseDto;
import com.xuecheng.domain.dto.CourseBaseInfoDto;
import com.xuecheng.domain.dto.EditCourseDto;
import com.xuecheng.domain.dto.QueryCourseParamsDto;
import com.xuecheng.domain.po.CourseBase;
import com.xuecheng.domain.po.CourseCategory;
import com.xuecheng.domain.po.CourseMarket;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程基本信息(CourseBase)表服务实现类
 *
 * @author makejava
 * @since 2024-03-30 22:35:08
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Resource
    CourseBaseMapper courseBaseMapper;

    @Resource
    CourseMarketMapper courseMarketMapper;

    @Resource
    CourseCategoryMapper courseCategoryMapper;

    //----------------------------------------课程查询------------------------------------------

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParams) {
        // 构建条件查询器
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        // 构建查询条件：按照课程名称模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParams.getCourseName()), CourseBase::getName, queryCourseParams.getCourseName());
        // 构建查询条件，按照课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParams.getAuditStatus());
        // 构建查询条件，按照课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getPublishStatus()), CourseBase::getStatus, queryCourseParams.getPublishStatus());
        // 分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageInfo = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> items = pageInfo.getRecords();
        // 获取数据总条数
        long counts = pageInfo.getTotal();
        // 构建结果集
        return new PageResult<>(items, counts, pageParams.getPageNo(), pageParams.getPageSize());
    }


    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //参数的合法性校验
        if (StringUtils.isBlank(addCourseDto.getName())) {
            throw new RuntimeException("课程名称不能为空");
        }
        if (StringUtils.isBlank(addCourseDto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }
        if (StringUtils.isBlank(addCourseDto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }
        if (StringUtils.isBlank(addCourseDto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }
        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }
        if (StringUtils.isBlank(addCourseDto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }
        if (StringUtils.isBlank(addCourseDto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }
        //向课程基本信息表course_base写入数据
        CourseBase courseBase = new CourseBase();
        //将页面传递过来的数据封装到courseBase对象中
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setAuditStatus(CourseEnum.AUDIT_STATUS_NO);
        courseBase.setStatus(CourseEnum.PUBLISH_NO);
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0) {
            throw new RuntimeException("课程基本信息插入失败");
        }
        //向课程营销表course_market写入数据
        CourseMarket courseMarket = new CourseMarket();
        Long courseBaseId = courseBase.getId();
        courseMarket.setId(courseBaseId);
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setCharge(CourseEnum.AUDIT_STATUS_NO);
        //保存营销信息
        saveCourseMarket(courseMarket);

        return getCourseBaseInfo(courseBaseId);
    }

    private void saveCourseMarket(CourseMarket courseMarket) {
        //校验营销数据是否为空
        CourseEnum charge = courseMarket.getCharge();
        if (charge == null) {
            throw new RuntimeException("收费规则为空");
        }
        if (charge.equals(CourseEnum.AUDIT_STATUS_NO)) {
            if (courseMarket.getPrice() == null) {
                throw new RuntimeException("课程的价格不能为空并且必须大于0");
            }
            //从数据库查询营销信息，逻辑：存在即更新，不存在则添加
            Long id = courseMarket.getId();
            CourseMarket courseMarket1 = courseMarketMapper.selectById(id);
            if (courseMarket1 == null) {
                courseMarketMapper.insert(courseMarket);
            } else {
                BeanUtils.copyProperties(courseMarket, courseMarket1);
                courseMarket1.setId(courseMarket.getId());
                courseMarketMapper.updateById(courseMarket1);
            }
        }
    }


    //查询课程信息
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        //从课程信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        //从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //组装到一起
        CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseMarket, courseBaseInfo);
        BeanUtils.copyProperties(courseBase, courseBaseInfo);
        //通过courseCategoryMapper查询课程分类信息
        // 3. 查询课程分类名称，并设置属性
        // 3.1 根据小分类id查询课程分类对象
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        // 3.2 设置课程的小分类名称
        courseBaseInfo.setStName(courseCategoryBySt.getName());
        // 3.3 根据大分类id查询课程分类对象
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        // 3.4 设置课程大分类名称
        courseBaseInfo.setMtName(courseCategoryByMt.getName());
        return courseBaseInfo;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        // 判断当前修改课程是否属于当前机构
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("只允许修改本机构的课程");
        }
        // 拷贝对象
        BeanUtils.copyProperties(editCourseDto, courseBase);
        // 更新，设置更新时间
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseMapper.updateById(courseBase);
        // 查询课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        // 由于课程营销信息不是必填项，故这里先判断一下
        if (courseMarket == null) {
            courseMarket = new CourseMarket();
        }
        courseMarket.setId(courseId);
        // 获取课程收费状态并设置
        CourseEnum charge = EnumUtils.getEnum(CourseEnum.class, editCourseDto.getCharge());
        courseMarket.setCharge(charge);
        // 如果课程收费，则判断价格是否正常
        // 对象拷贝
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        // 有则更新，无则插入
        courseMarketMapper.updateById(courseMarket);
        return getCourseBaseInfo(courseId);
    }

}
